﻿using System;
using System.Net;
using System.Linq;
using System.Text;
using Enyim.Caching;
using System.Net.Mail;
using SilenthinkContract;
using System.Threading.Tasks;
using System.ComponentModel;
using SilenthinkContract.Domain;
using SilenthinkCommon.Extension;
using SilenthinkContract.Component;

namespace SilenthinkService
{
    public class MsmqService : IMsmqService
    {
        private readonly IBaseService baseService;
        private readonly IStoreService storeService;
        private readonly IExtraService extraService;
        private readonly IMemcachedClient cache;
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
        public MsmqService()
        {
            baseService = new BaseService();
            storeService = new StoreService();
            extraService = new ExtraService();
            cache = new MemcachedClient();
        }
        public void Register(RegisterLog log)
        {
            extraService.CreateRegisterLog(log);
            var mails = cache.Put(CacheKey.Base.EmailAccount, baseService.GetAllEmailAccount);
            var templates = cache.Put(CacheKey.Base.EmailTemplate, baseService.GetAllEmailTemplate);
            var mail = mails.FirstOrDefault(o => o.Status && o.Category == EmailAccountCategory.Register);
            var template = templates.FirstOrDefault(o => o.Id == 1);
            Task.Factory.StartNew(() => SendEmail(log, mail, template));
        }
        private static void SendEmail(RegisterLog log, EmailAccount mail, EmailTemplate template)
        {
            var from = new MailAddress(mail.Email, mail.DisplayName);
            var to = new MailAddress(log.UserName);

            using (var client = new SmtpClient(mail.Host, mail.Port))
            using (var message = new MailMessage(from, to))
            {
                message.IsBodyHtml = true;
                message.Priority = MailPriority.High;

                if (!string.IsNullOrEmpty(template.BccEmailAddresses))
                {
                    foreach (var o in template.BccEmailAddresses.Split(',').Where(o => o.IsEmail()))
                    {
                        message.Bcc.Add(o);
                    }
                }
                message.Subject = template.Subject;
                message.SubjectEncoding = Encoding.UTF8;

                message.Body = log.Id.ToString();
                message.BodyEncoding = Encoding.UTF8;

                client.EnableSsl = mail.EnableSsl;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = mail.UseDefaultCredentials;
                client.Credentials = new NetworkCredential(mail.Username, mail.Password);

                try
                {
                    client.Send(message);
                    Logger.Trace("发送邮件成功：" + log.Id);
                }
                catch (Exception e)
                {
                    Logger.Trace("发送邮件异常：" + log.Id + e.Message);
                }
            }
        }
    }
}